const Service = require('egg').Service;
const jwt = require('jsonwebtoken')

class UserService extends Service {
  async login() {
    const { app, ctx } = this;
    const { username, password } = ctx.request.body;
    const data = await app.mysql.get('users', {
      username: username,
      password: this.ctx.helper.getPassword(password)
    })
    if (data) {
      const token = jwt.sign({ ...data }, app.config.keys, { expiresIn: '24h' })
      return { code: 0, msg: '登陆成功', token }
    } else {
      return { code: -1, msg: '登陆失败' }
    }
  }

  async register() {
    const { app, ctx } = this;
    const { username, password, nickname } = ctx.request.body;

    const data = await app.mysql.get('users', { username })
    // select * from users where username=?

    if (data) {
      return { code: -1, msg: '账号已经存在' }
    } else {
      const data = await app.mysql.insert('users', {
        username,
        password: this.ctx.helper.getPassword(password),
        nickname
      })
      if (data.affectedRows) {
        return { code: 0, msg: '注册成功', id: data.insertId }
      } else {
        return { code: -1, msg: '注册失败' }
      }
    }
  }
}

module.exports = UserService;